/**
 * WebSocket连接管理类
 * 用于语音流式处理的实时通信 - 按用户管理
 */

export interface WebSocketMessage {
  type: 'PROGRESS_UPDATE' | 'TASK_COMPLETED' | 'TASK_FAILED' | 'CONNECTED'
  taskId?: string
  data?: {
    status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED'
    progress: number
    currentStep?: string
    message?: string
    recognizedText?: string
    aiReply?: string
    voiceUrl?: string
    userVoiceUrl?: string
    fileSize?: number
    duration?: number
    errorCode?: string
    errorMessage?: string
    conversationId?: number
    timestamp: string
  }
  message?: string
  userId?: string
  timestamp?: string
}

export interface VoiceTaskWebSocketOptions {
  maxReconnectAttempts?: number
  reconnectInterval?: number
  onProgressUpdate?: (taskId: string, data: WebSocketMessage['data']) => void
  onTaskCompleted?: (taskId: string, data: WebSocketMessage['data']) => void
  onTaskFailed?: (taskId: string, data: WebSocketMessage['data']) => void
  onError?: (error: string) => void
  onConnect?: () => void
  onDisconnect?: () => void
}

export class VoiceTaskWebSocket {
  private userId: string
  private ws: WebSocket | null = null
  private reconnectAttempts = 0
  private maxReconnectAttempts: number
  private reconnectInterval: number
  private options: VoiceTaskWebSocketOptions
  private isManualClose = false
  private taskHandlers: Map<string, (type: string, data: any) => void> = new Map()

  constructor(userId: string, options: VoiceTaskWebSocketOptions = {}) {
    this.userId = userId
    this.maxReconnectAttempts = options.maxReconnectAttempts || 5
    this.reconnectInterval = options.reconnectInterval || 1000
    this.options = options
  }

  /**
   * 建立WebSocket连接
   */
  connect(): void {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      console.log('WebSocket已连接，跳过重复连接')
      return
    }

    const wsUrl = `ws://localhost:8080/ws/voice-task/user/${this.userId}`
    console.log('🔌 正在连接WebSocket:', wsUrl)
    console.log('🔌 连接时间:', new Date().toISOString())
    
    try {
      this.ws = new WebSocket(wsUrl)
      this.setupEventListeners()
      
      // 添加连接状态检查定时器
      const checkInterval = setInterval(() => {
        if (this.ws) {
          console.log('🔍 WebSocket状态检查:', {
            readyState: this.ws.readyState,
            url: this.ws.url,
            userId: this.userId
          })
          
          if (this.ws.readyState === WebSocket.CLOSED || this.ws.readyState === WebSocket.CLOSING) {
            console.log('🔍 WebSocket已关闭，清除检查定时器')
            clearInterval(checkInterval)
          }
        }
      }, 2000)
      
      // 10秒后清除定时器
      setTimeout(() => {
        clearInterval(checkInterval)
        console.log('🔍 清除WebSocket状态检查定时器')
      }, 10000)
      
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.options.onError?.('WebSocket连接失败: ' + error)
    }
  }

  /**
   * 设置WebSocket事件监听器
   */
  private setupEventListeners(): void {
    if (!this.ws) return

    this.ws.onopen = () => {
      console.log('✅ WebSocket连接已建立:', this.userId)
      console.log('✅ WebSocket状态:', this.ws?.readyState)
      console.log('✅ WebSocket URL:', this.ws?.url)
      this.reconnectAttempts = 0
      this.isManualClose = false
      this.options.onConnect?.()
    }

    this.ws.onmessage = (event) => {
      console.log('🔔 收到WebSocket原始消息:', event.data)
      console.log('🔔 消息类型:', typeof event.data)
      console.log('🔔 消息长度:', event.data.length)
      
      try {
        const message: WebSocketMessage = JSON.parse(event.data)
        console.log('✅ 解析后的WebSocket消息:', message)
        console.log('✅ 消息类型:', message.type)
        console.log('✅ 任务ID:', message.taskId)
        console.log('✅ 数据内容:', message.data)
        this.handleMessage(message)
      } catch (error) {
        console.error('❌ 解析WebSocket消息失败:', error)
        console.error('❌ 原始消息内容:', event.data)
        console.error('❌ 错误详情:', error.message)
        this.options.onError?.('消息解析失败')
      }
    }

    this.ws.onclose = (event) => {
      console.log('❌ WebSocket连接已关闭:', event.code, event.reason)
      console.log('❌ 关闭原因:', event.wasClean ? '正常关闭' : '异常关闭')
      console.log('❌ 是否手动关闭:', this.isManualClose)
      this.options.onDisconnect?.()
      
      // 如果不是手动关闭且任务未完成，尝试重连
      if (!this.isManualClose && event.code !== 1000) {
        console.log('🔄 尝试重连...')
        this.reconnect()
      }
    }

    this.ws.onerror = (error) => {
      console.error('❌ WebSocket错误:', error)
      console.error('❌ WebSocket状态:', this.ws?.readyState)
      this.options.onError?.('WebSocket连接错误')
    }
  }

  /**
   * 处理WebSocket消息
   */
  private handleMessage(message: WebSocketMessage): void {
    const { type, taskId, data } = message
    
    // 处理全局消息（如CONNECTED）
    if (type === 'CONNECTED' || !taskId) {
      this.handleGlobalMessage(type, data)
      return
    }
    
    // 根据taskId路由到对应的任务处理器
    if (taskId && this.taskHandlers.has(taskId)) {
      const handler = this.taskHandlers.get(taskId)
      handler?.(type, data)
    } else {
      console.warn('📨 未找到任务处理器:', taskId, type)
      // 如果有通用处理器，使用通用处理器
      if (this.options.onProgressUpdate || this.options.onTaskCompleted || this.options.onTaskFailed) {
        console.log('📨 使用通用处理器处理消息:', taskId, type)
        this.handleWithGenericHandlers(type, data)
      }
    }
  }

  /**
   * 使用通用处理器处理消息
   */
  private handleWithGenericHandlers(type: string, data: any): void {
    switch (type) {
      case 'PROGRESS_UPDATE':
        this.options.onProgressUpdate?.('', data)
        break
      case 'TASK_COMPLETED':
        this.options.onTaskCompleted?.('', data)
        break
      case 'TASK_FAILED':
        this.options.onTaskFailed?.('', data)
        break
    }
  }

  /**
   * 处理全局消息
   */
  private handleGlobalMessage(type: string, data: any): void {
    switch (type) {
      case 'CONNECTED':
        console.log('🔗 WebSocket连接确认:', data)
        // 触发连接成功回调
        this.options.onConnect?.()
        break
      default:
        console.log('📨 全局消息:', type, data)
    }
  }

  /**
   * 注册任务处理器
   */
  registerTaskHandler(taskId: string, handler: (type: string, data: any) => void): void {
    this.taskHandlers.set(taskId, handler)
    console.log('📝 注册任务处理器:', taskId)
  }

  /**
   * 取消注册任务处理器
   */
  unregisterTaskHandler(taskId: string): void {
    this.taskHandlers.delete(taskId)
    console.log('🗑️ 取消注册任务处理器:', taskId)
  }

  /**
   * 重连机制
   */
  private reconnect(): void {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket重连失败，已达到最大重连次数')
      this.options.onError?.('WebSocket重连失败，请刷新页面重试')
      return
    }

    this.reconnectAttempts++
    const delay = this.reconnectInterval * Math.pow(2, this.reconnectAttempts - 1)
    console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})，延迟 ${delay}ms`)

    setTimeout(() => {
      this.connect()
    }, delay)
  }

  /**
   * 断开WebSocket连接
   */
  disconnect(): void {
    this.isManualClose = true
    if (this.ws) {
      this.ws.close(1000, '用户主动断开')
      this.ws = null
    }
    // 清理所有任务处理器
    this.taskHandlers.clear()
  }

  /**
   * 检查连接状态
   */
  isConnected(): boolean {
    return this.ws?.readyState === WebSocket.OPEN
  }

  /**
   * 获取连接状态
   */
  getReadyState(): number {
    return this.ws?.readyState ?? WebSocket.CLOSED
  }

  /**
   * 获取用户ID
   */
  getUserId(): string {
    return this.userId
  }

  /**
   * 获取活跃任务数量
   */
  getActiveTaskCount(): number {
    return this.taskHandlers.size
  }
}